package chap03.BubbleSort;

/**
 * Created by root on 2017/7/12.
 */
public class ArrayBub{
    private long[] a;
    private int nElems;

    public ArrayBub(int max){
        a = new long[max];
        nElems = 0;
    }

    public void insert(long value){
        a[nElems] = value;
        nElems++;
    }

    public void display(){
        for (int j=0; j<nElems; j++) {
            System.out.print(a[j] + "  ");
        }
        System.out.println();
    }

    public void bubbleSort() {
        int outer, inner;
        int compareNum = 0;
        int exchangeNum = 0;
        for (outer=nElems-1; outer>0; outer--) {
            for (inner=0; inner<outer; inner++) {
                compareNum++;
                if (a[inner] > a[inner+1]) {
                    exchangeNum++;
                    swap(inner, inner+1);
                }
            }
        }
        System.out.println("bubblesort compareNum is " + compareNum + " 次");
        System.out.println("bubblesort exchangeNum is " + exchangeNum + " 次");
    }

    public void oddEvenSort(){
        boolean change = true;
        while (change) {
            change = false;
            for (int j=1; j<nElems-1; j=j+2) {
                if (a[j] > a[j+1]) {
                    swap(j,j+1);
                    change = true;
                }
            }
            for (int j=0; j<nElems-1; j=j+2) {
                if (a[j] > a[j+1]) {
                    swap(j,j+1);
                    change = true;
                }
            }
        }

    }

    public void swap(int one, int two) {
        long temp = a[two];
        a[two] = a[one];
        a[one] = temp;
    }
}
